package com.king.utils;

import com.google.gson.JsonObject;
import com.king.config.GlobalConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Formatter;
import java.util.Random;

public class WxUtils {

    private static Logger log = LoggerFactory.getLogger(WxUtils.class);

    /**
     * 1.发起https请求并获取结果
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     * @return JsonObject(com.google.gson.JsonObject)
     */
    public static JsonObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JsonObject jsonObject = null;
        HttpsURLConnection httpUrlConn = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            TrustManager[] tm = {new MyX509TrustManager()};// 创建SSLContext对象，并使用我们指定的信任管理器初始化
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();// 从上述SSLContext对象中得到SSLSocketFactory对象

            URL url = new URL(requestUrl);
            httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestMethod(requestMethod);// 设置请求方式（GET/POST）

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            if (null != outputStr) {// 当有数据需要提交时
                OutputStream outputStream = null;
                try {
                    outputStream = httpUrlConn.getOutputStream();
                    outputStream.write(outputStr.getBytes("UTF-8"));// 注意编码格式，防止中文乱码
                } finally {
                    outputStream.close();
                }
            }

            inputStream = httpUrlConn.getInputStream();// 将返回的输入流转换成字符串
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonObject = GlobalConst.gson.fromJson(buffer.toString(), JsonObject.class);
        } catch (ConnectException ce) {
            log.error("Weixin server connection timed out.");
        } catch (Exception e) {
            log.error("https request error:{}", e);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 释放资源
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (httpUrlConn != null) {
                httpUrlConn.disconnect();
            }
        }
        return jsonObject;
    }

    /**
     * 2.发起http请求获取返回结果
     *
     * @param requestUrl 请求地址
     * @return
     */
    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
        HttpURLConnection httpUrlConn = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            httpUrlConn = (HttpURLConnection) url.openConnection();

            httpUrlConn.setDoOutput(false);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            httpUrlConn.setRequestMethod(requestMethod);//"GET/POST"
            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            if (null != outputStr) {// 当有数据需要提交时
                OutputStream outputStream = null;
                try {
                    outputStream = httpUrlConn.getOutputStream();
                    outputStream.write(outputStr.getBytes("UTF-8"));// 注意编码格式，防止中文乱码
                } finally {
                    outputStream.close();
                }
            }

            inputStream = httpUrlConn.getInputStream(); // 将返回的输入流转换成字符串
            //InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {  // 释放资源
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (httpUrlConn != null) {
                httpUrlConn.disconnect();
            }
        }
        return buffer.toString();
    }

    /**
     * 发送https请求之获取临时素材
     * 下载临时素材
     *
     * @param requestUrl
     * @param savePath   文件的保存目录
     * @return
     * @throws Exception
     */
    public static File downloadMedia(String requestUrl, String savePath) {
        HttpsURLConnection httpUrlConn = null;
        InputStream in = null;
        FileOutputStream out = null;

        try {
            //String path=System.getProperty("user.dir")+"/img//1.png";

            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("GET");

            httpUrlConn.connect();

            //获取文件扩展名
            String ext = getExt(httpUrlConn.getContentType());
            String fileName = System.currentTimeMillis() + "";
            savePath = savePath + "\\" + fileName + ext;
            System.out.println("savePath: " + savePath);

            //下载文件到f文件
            File file = new File(savePath);

            // 获取微信返回的输入流
            in = httpUrlConn.getInputStream();

            //输出流，将微信返回的输入流内容写到文件中
            out = new FileOutputStream(file);

            int length = 100 * 1024;
            byte[] byteBuffer = new byte[length]; //存储文件内容

            int byteread;
            int bytesum = 0;
            while ((byteread = in.read(byteBuffer)) != -1) {
                bytesum += byteread; //字节数 文件大小
                out.write(byteBuffer, 0, byteread);
            }
            System.out.println("byteSum: " + bytesum);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {// 释放资源
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpUrlConn != null) {
                httpUrlConn.disconnect();
            }
        }

        return null;
    }

    /**
     * 微信上传素材的请求方法http 上传文件）
     *
     * @param requestUrl 微信上传临时素材的接口url
     * @param file       要上传的文件
     * @return String  上传成功后，微信服务器返回的消息
     */
    public static String uploadMedia(String requestUrl, File file) {
        HttpURLConnection httpUrlConn = null;
        OutputStream outputStream = null;
        DataInputStream in = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        StringBuffer buffer = new StringBuffer();
        try {
            //1.建立连接
            URL url = new URL(requestUrl);
            httpUrlConn = (HttpURLConnection) url.openConnection();  //打开链接

            //1.1输入输出设置
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setUseCaches(false); // post方式不能使用缓存

            //1.2设置请求头信息
            httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
            httpUrlConn.setRequestProperty("Charset", "UTF-8");
            //1.3设置边界
            String BOUNDARY = "----------" + System.currentTimeMillis();
            httpUrlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            // 获得输出流
            outputStream = new DataOutputStream(httpUrlConn.getOutputStream());

            // 请求正文信息
            // 第一部分：
            //2.将文件头输出到微信服务器
            StringBuilder sb = new StringBuilder();
            sb.append("--"); // 必须多两道线
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
                    + "\";filename=\"" + file.getName() + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] head = sb.toString().getBytes("utf-8");
            // 将表头写入输出流中：输出表头
            outputStream.write(head);

            //3.将文件正文部分输出到微信服务器
            // 把文件以流文件的方式 写入到微信服务器中
            in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                outputStream.write(bufferOut, 0, bytes);
            }

            //4.将结尾部分输出到微信服务器
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
            outputStream.write(foot);

            outputStream.flush();

            //5.将微信服务器返回的输入流转换成字符串
            inputStream = httpUrlConn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);

            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        } finally {// 释放资源
            if (httpUrlConn != null) {
                httpUrlConn.disconnect();
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer.toString();
    }

    /**
     * 方法名：byteToHex</br>
     * 详述：字符串加密辅助方法 </br>
     *
     * @param hash
     * @return 说明返回值含义
     */
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    /**
     * 获取请求文件的后缀
     *
     * @param contentType
     * @return
     */
    private static String getExt(String contentType) {
        if ("image/jpeg".equals(contentType)) {
            return ".jpg";
        } else if ("image/png".equals(contentType)) {
            return ".png";
        } else if ("image/gif".equals(contentType)) {
            return ".gif";
        }
        return null;
    }
}
